<?php
namespace app\common\service\weixin;

use app\common\components\HttpClient;
use app\common\service\BaseService;

class PayApiService extends BaseService
{
    private $params = [];
    private $wxpay_params = [];
    private $prepay_id = null;
    private $prepay_info = null;

    public function __construct( $wxpay_params )
    {
        $this->wxpay_params = $wxpay_params;
    }

    public function setParameter( $parameter,$parameterValue ){
        $this->params[ $parameter ] = $parameterValue;
    }

    public function getPrepayInfo(){
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $this->params['nonce_str'] = $this->createNoncestr();
        $this->params['sign'] = $this->getSign( $this->params );
        $xml_data = $this->arrayToXml( $this->params );
        $ret = HttpClient::post( $url,$xml_data );

        if( $ret ){
            $wx_order = $this->xmlToArray( $ret );
            $this->prepay_info = $wx_order;
            if( isset( $wx_order['result_code']) && $wx_order['result_code'] == "SUCCESS"  ){
                return $wx_order;
            }
            return false;
        }
    }

    function setPrepayId($prepay_id){
        $this->prepay_id = $prepay_id;
    }


    //生成随机字符串
    public function createNoncestr( $length = 32 ){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = '';
        for( $i = 0;$i < $length;$i++ ){
            $str .= substr( $chars,mt_rand(0,strlen($chars)-1),1 );
        }  //substr($obj,$start,$length);

        return $str;
    }

    //获取签名
    public function getSign( $Obj ){
        foreach( $Obj as $k => $v ){
            $Parameters[$k] = $v;
        }
        ksort( $Parameters );
        $String = $this->formatBizQueryParaMap( $Parameters,false );
        $String = $String."&key=".$this->wxpay_params['pay']['key'];
        $String = md5( $String );
        $result_ = strtoupper( $String );
        return $result_;
    }

    /**
     * 作用：格式化参数，签名过程需要使用
     */
    private function formatBizQueryParaMap( $paraMap,$urlencode ){
        $buff = '';
        ksort( $paraMap );
        foreach( $paraMap as $k => $v ){
            if( $urlencode ){
                $v = urlencode( $v );
            }
            $buff .= $k."=".$v."&";
        }
        $reqPar = '';
        if( strlen( $buff ) > 0 ){
            $reqPar = substr( $buff,0,strlen( $buff ) -1 );
        }

        return $reqPar;
    }

    /**
     * 作用：设置jsapi的参数
     */
    public function getParameters(){
//        timestamp、 nonceStr、package:prepay_id=、signType、paySign
        $jsApiObj['appId'] = $this->wxpay_params['appid'];
        $jsApiObj['timestamp'] = time();
        $jsApiObj['nonceStr'] = $this->createNoncestr();
        $jsApiObj['package'] = "prepay_id=".$this->prepay_id;
        $jsApiObj['signType'] = "MD5";
        $jsApiObj['paySign'] = $this->getSign( $jsApiObj );
        return $jsApiObj;
    }

    public function arrayToXml( $arr ){
        $xml = "<xml>";
        foreach( $arr as $key => $val ){
            if( is_numeric( $val ) ){
                $xml .= "<". $key .">".$val."</".$key.">";
            }else{
                $xml .= "<". $key ."><![CDATA[".$val."]]></". $key .">";
            }
        }

        $xml .= "</xml>";
        return $xml;
    }

    public function xmlToArray( $xml ){
        $array_data = json_decode(json_encode(simplexml_load_string( $xml,"SimpleXMLElement",LIBXML_NOCDATA )),true);
        return $array_data;
    }


    //验证签名
    public function checkSign( $sign )
    {
        $tmpData = $this->params;
        $wxpay_sign = $this->getSign( $tmpData );
        if( $wxpay_sign == $sign ){
            return true;
        }
        return false;

    }


}